<?php

namespace app\controllers;

use Yii;
use app\models\Qa;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\Pagination;
use app\models\Users;
use app\models\Qa_tag;
use app\models\Comments;
use app\controllers\BaseController;

/**
 * QaController implements the CRUD actions for Qa model.
 */
class QaController extends BaseController {

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['create', 'update', 'delete'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 问答列表(最新)
     * @return mixed
     */
    public function actionIndex() {
        //获取最新列表
        $query = Qa::find()->where(['status' => '1']);
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $qa_list = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->orderBy('id desc')
                ->all();

        return $this->render('index', ['qa_list' => $qa_list, 'pages' => $pages]);
    }

    /**
     * 热门问答
     * @return type
     */
    public function actionHot() {
        //获取最新列表
        $query = Qa::find()->where(['status' => '1']);
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $qa_list = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->orderBy('view desc')
                ->all();

        return $this->render('hot', ['qa_list' => $qa_list, 'pages' => $pages]);
    }

    /**
     * Displays a single Qa model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        //1、获取问答信息
        $question = Qa::findOne($id);
        if (!$question) {
            throw new NotFoundHttpException('你所请求的页面不存在.');
        }
        Qa::view_add($id);
        //2、获取tag标签
        $tags = Qa_tag::get_show_tags($id);
        //3、获取作者信息
        $author = Users::findOne($question['uid']);
        //4、获取评论信息
        $comments = Comments::find()->where(['type' => 'qa', 'rid' => $id])->orderBy('best_answer desc')->all();
        //5、获取最佳答案
        $best_answer = Comments::findOne(['type' => 'qa', 'rid' => $id, 'best_answer' => '1']);
        //6、评论form
        $model_comment = new Comments();
        //7、判断当前登陆用户是否已经评论
        $is_comment = false;
        if (Yii::$app->user) {
            $result = Comments::findOne(['type' => 'qa', 'rid' => $id, 'uid' => Yii::$app->user->identity->id]);
            if ($result) {
                $is_comment = true;
            }
        }
        if ($author->id == Yii::$app->user->identity->id) {
            $is_comment = true;
        }


        //数据组装
        $data = [
            'question' => $question,
            'tags' => $tags,
            'author' => $author,
            'comments' => $comments,
            'best_answer' => $best_answer,
            'model_comment' => $model_comment,
            'is_comment' => $is_comment
        ];
        return $this->render('view', $data);
    }

    /**
     * Creates a new Qa model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $post = Yii::$app->request->post();
        $model = new Qa();
        $model_qa_tag = new Qa_tag();
        if ($model->load($post) && $model->save()) {
            //创建qa成功，添加tags
            $model_qa_tag->save_tags($model, $post['Qa']['tags']);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Qa model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        //判断该用户是否具有该问答操作权限
        Qa::check_access($id, Yii::$app->user->identity->id);

        $post = Yii::$app->request->post();
        $model = $this->findModel($id);
        $model_qa_tag = new Qa_tag();
        $tags = Qa_tag::get_edit_tags($id);
        $model->tags = $tags;
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            //编辑qa成功，编辑tags
            $model_qa_tag->update_tag($model, $post['Qa']['tags']);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Qa model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        //判断该用户是否具有该问答操作权限
        Qa::check_access($id, Yii::$app->user->identity->id);

        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Qa model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Qa the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Qa::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('你所请求的页面不存在.');
        }
    }

    /**
     * 设置为最佳答案
     */
    public function actionAdopt($qid, $answer_id) {
        //判断该用户是否具有该问答操作权限
        Qa::check_access($qid, Yii::$app->user->identity->id);

        //判断该问答是否已经具有最佳答案了
        $result = Comments::findOne(['type' => 'qa', 'rid' => $qid, 'best_answer' => '1']);
        if ($result) {
            $session->setFlash('message', '该问答已经具有最佳答案，不能重复采纳');
            return $this->redirect('/site/message');
        }

        //采纳
        $comment = Comments::findOne(['id' => $answer_id]);
        $comment->best_answer = '1';
        $comment->save();
        return $this->redirect(['/qa/view', 'id' => $qid]);
    }

}
